<template>
  <el-upload
          class="upload-demo"
          drag
          :action="action"
          multiple
          :before-upload="beforeUpload"
          :data="data"
          :on-success="handleSuccess"
          :file-list="list"
          :on-remove="handleRemove"
          :on-preview="preview"
  >
    <i class="el-icon-upload" />
    <div class="el-upload__text">
      将文件拖到此处，或
      <em>点击上传</em>
    </div>
    <div slot="tip" class="el-upload__tip">文件不能超过20M</div>
  </el-upload>
</template>

<script>
  import API from '@/api/common/adjunct'
  export default {
    props: {
      table: {
        type: String,
        default: ''
      },
      pk: {
        type: Number,
        default: 0
      }
    },
    data() {
      return {
        action: 'https://router.ubeiyun.com/api/v1/adjunctAdd',
        list: []
      }
    },
    computed: {
      data() {
        return {
          table: this.table,
          id: this.pk
        }
      }
    },

    watch: {
      pk() {
        this.index()
      },
      table() {
        this.index()
      },
      list(newVal) {
        this.$emit('change', newVal)
      }
    },
    created() {
      this.index()
    },
    methods: {
      index() {
        API.index(this.data).then(response => {
          this.list = response.data.data
        })
      },
      handleSuccess(res) {
        this.list.push(res.data)
      },
      beforeUpload(file) {
        const isLt20M = file.size / 1024 / 1024 < 20
        if (!isLt20M) {
          this.$message.error('文件大小不能超过 20MB!')
        }
        return isLt20M
      },
      handleRemove(file) {
        API.delete(file.id)
      },
      preview(file) {
        window.open(file.path, 'hello')
      }
    }
  }
</script>

